﻿using System;
using System.Text;
using System.Windows;
using System.Net.NetworkInformation;
using System.Windows.Forms;
using System.Configuration;
using Application = System.Windows.Application;
using System.Threading;

namespace CUMTConnect
{
	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
	{
		// notify icon object 
		// will be used in Login class and initial tray
		private NotifyIcon notifyIcon = null;
		public MainWindow()
		{
			InitializeComponent();
			
			// let this app form show in screen center
			WindowStartupLocation = WindowStartupLocation.CenterScreen;

			Logger.Log.Info("Register Event Handler => NetworkChange_NetworkAvailabilityChanged");
			Logger.Log.Info("Register Event Handler => NetworkChange_NetworkAddressChanged");
			// listen network change
			NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
			NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;

			// Load startup config
			if (CUMTConnect.Boot.ShortCutExist())
			{
				this.Boot.IsChecked = true;
			}

			// check whether run one app and initial notify icon and tary
			if (RunOneCheck.CheckWhetherRunOne())
			{
				Logger.Log.Info("Initial notify ICON");
				InitialTray();
			}
			else
			{
				Logger.Log.Info("Another program is already running, Shutting Down this process");
				Application.Current.Shutdown();
			}

			// check if config is available
			if (Config.CheckConfig())
			{
				// available, then try to load config file and show it in the form
				LoadConfig();

				// if not login, then try to login
				if (!Login.IsLogIn())
				{
					Logger.Log.Info("Login with StudentID : {0} ", ConfigurationManager.AppSettings["StudentID"]);
					Login.LogIn(ref this.notifyIcon);
				}
			}
			else
			{
				// config file not exist
				if (!Config.ConfigFileExist())
				{
					Logger.Log.Info("Create a basic config file");
					// create a basic config file
					Config.ExtracBasicConfig();
				}

				// Notice form  to show notice
				Notice notice = new Notice("你还没有正确的配置此程序，在程序界面进行简单的配置吧！至少需要填好学号、密码以及选择好运营商！");
				notice.ShowDialog();

				// add default SSID
				this.WIFIList.Items.Add("CUMT_Stu");

				// show main window
				this.Visibility = Visibility.Visible;
				this.Activate();
			}
		}

		/**
		 * When windows network address changed, this function will be called automatically
		 * this function will judge the wifi you link if is in the list and then try to login in
		 */
		private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
		{
			Logger.Log.Info("NetworkAddressChanged");
			//throw new NotImplementedException();
			Login.LogIn(ref this.notifyIcon);
		}



		/**
		 * Create a notify icon and hidden main window
		 */
		private void InitialTray()
		{
			this.Visibility = Visibility.Hidden;
			notifyIcon = new NotifyIcon();
			notifyIcon.Text = "CUMTConnect: 软件一直在运行╮(╯▽╰)╭";
			notifyIcon.BalloonTipText = @"已自动登录到校园网";
			notifyIcon.Visible = true;
			notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
			notifyIcon.MouseDoubleClick += NotifyIcon_MouseDoubleClick;

			// Add Menu item
			MenuItem login = new MenuItem("立即登录");
			MenuItem exit = new MenuItem("退出程序");
			// Register event
			login.Click += Login_Click;
			exit.Click += Exit_Click;
			// link to noitfyIcon
			notifyIcon.ContextMenu = new ContextMenu(new MenuItem[] { login, exit });


			// prevent window close, if the setting ClickXClose was set as true, then it will exit
			this.Closing += MainWindow_Closing;
			this.StateChanged += MainWindow_StateChanged;
		}

		/**
		 * Exit this application
		 */
		private void Exit_Click(object sender, EventArgs e)
		{
			//throw new NotImplementedException();
			Application.Current.Shutdown();
		}

		/**
		 * Login now
		 */
		private void Login_Click(object sender, EventArgs e)
		{
			//throw new NotImplementedException();
			Login.LogIn(ref this.notifyIcon);
		}

		/**
		 * Prevent window closing, if config ClickXClose set to true then let this program exit
		 */
		private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			//throw new NotImplementedException();
			if (!Convert.ToBoolean(ConfigurationManager.AppSettings["ClickXClose"]))
			{
				e.Cancel = true;
				this.Visibility = Visibility.Hidden;
			}
			else
			{
				e.Cancel = false;
			}
		}

		/**
		 * When Window state changed, this function will be called automatically
		 * this function let the window to hide
		 */
		private void MainWindow_StateChanged(object sender, EventArgs e)
		{
			//throw new NotImplementedException();
			if (this.WindowState == WindowState.Minimized)
			{
				this.Visibility = Visibility.Hidden;
			}
		}

		/**
		 * When the user double click the notify icon, this function will be called automatically
		 * this function will activate the window and show it
		 */
		private void NotifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			//throw new NotImplementedException();
			if (e.Button == MouseButtons.Left)
			{
				if (this.Visibility == Visibility.Visible)
				{
					this.Visibility = Visibility.Hidden;
				}
				else
				{
					this.Visibility = Visibility.Visible;
					this.Activate();
				}
			}
		}

		/**
		 * When windows network availability changed, this function will be called automatically
		 * this function will judge the wifi you link if is in the list and then try to login in
		 */
		private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
		{
			Logger.Log.Info("NetworkAvailabilityChanged");
			//throw new NotImplementedException();
			// auto login
			Login.LogIn(ref this.notifyIcon);
		}

		/**
		 * open a new window and scan wifi list then show it in the new window
		 */
		private void Button_Click(object sender, RoutedEventArgs e)
		{
			WIFIAddedForm waf = new WIFIAddedForm();
			waf.ShowDialog();
			AddSSIDToList(waf.SSID);
			waf = null;
		}

		/**
		 * Add a SSID to ListView component
		 * when try to save config, it will auto be stringified
		 */
		public void AddSSIDToList(String SSID)
		{
			if (this.WIFIList.Items.Contains(SSID) || SSID == "")
			{
				return;
			}
			else
			{
				this.WIFIList.Items.Add(SSID);
			}
		}

		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
			this.WIFIList.Items.Remove(this.WIFIList.SelectedItem);
		}

		private void Button_Click_2(object sender, RoutedEventArgs e)
		{
			Application.Current.Shutdown();
		}

		/**
		 * Try to load config from APP config file
		 */
		private void LoadConfig()
		{
			Config.LoadConfig(this);
		}

		/**
		 * Save config to config file
		 */
		private void Button_Click_3(object sender, RoutedEventArgs e)
		{
			Config.SaveConfig(this);
		}

		/**
		 * Launch this app when system boot
		 */
		private void Boot_Checked(object sender, RoutedEventArgs e)
		{
			if (CUMTConnect.Boot.ShortCutExist())
			{
				return;
			}
			Logger.Log.Info("Add auto start");
			String origin = notifyIcon.BalloonTipText;
			if (CUMTConnect.Boot.StartAutomatically())
			{
				notifyIcon.BalloonTipText = @"已添加到开机启动项！";
			}
			else
			{
				notifyIcon.BalloonTipText = @"在尝试添加至开机启动项时失败，详情请见日志文件！";
			}
			notifyIcon.ShowBalloonTip(2000);
			notifyIcon.BalloonTipText = origin;
		}

		private void Boot_UnChecked(object sender, RoutedEventArgs e)
		{
			Logger.Log.Info("Remove auto start");
			String origin = notifyIcon.BalloonTipText;
			if (CUMTConnect.Boot.DelAutoStart())
			{
				notifyIcon.BalloonTipText = @"取消开机启动项成功！";
			}
			else
			{
				notifyIcon.BalloonTipText = @"在尝试移除本程序的开机启动项时失败，详情请见日志文件！";
			}
			notifyIcon.ShowBalloonTip(2000);
			notifyIcon.BalloonTipText = origin;
		}


	}
}
